package com.creative.xcx.controller;

import cn.hutool.core.lang.UUID;
import com.aliyuncs.exceptions.ClientException;
import com.creative.core.controller.BaseController;
import com.creative.core.domain.AjaxResult;
import com.creative.core.page.TableDataInfo;
import com.creative.core.uitls.oss.AliOssUtil;
import com.creative.user.service.UserInfoService;
import com.creative.xcx.domain.XcxPageData;
import com.creative.xcx.service.MaterialService;
import com.creative.xcx.service.MaterialTypeService;
import com.creative.xcx.service.UploadHistoryService;
import com.creative.xcx.service.XcxPageDataService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;


/**
 * 小程序页面数据
 *
 * @author ling
 * @description 小程序的页面数据(eg : Banner图片 ， 分类封面之类的)
 * @date 2025-01-15
 */
@RestController
@RequestMapping(value = "/XcxPageData")
public class XcxPageDataController extends BaseController {

    @Resource
    private XcxPageDataService xcxPageDataService;

    @Resource
    private AliOssUtil aliOssUtil;
    @Resource
    private MaterialService materialService;
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private MaterialTypeService materialTypeService;
    @Resource
    private UploadHistoryService uploadHistoryService;

    /**
     * 新增
     *
     * @author ling
     * @date 2025/01/15
     **/
    @PostMapping
    public AjaxResult insert(@RequestBody XcxPageData xcxPageData) {
        return toAjax(xcxPageDataService.insert(xcxPageData));
    }

    /**
     * 刪除数据库中数据
     * 逻辑删除
     *
     * @author ling
     * @date 2025/01/15
     **/
    @DeleteMapping
    public AjaxResult delete(@RequestBody String pdId) {
        logger.info("删除数据库中数据：{}", pdId);
        if (pdId == null) {
            return error("参数为空");
        }
        return toAjax(xcxPageDataService.delete(pdId));
    }

    /**
     * 更新
     *
     * @author ling
     * @date 2025/01/15
     **/
    @PutMapping("/update")
    public AjaxResult update(@RequestBody XcxPageData xcxPageData) {
        return toAjax(xcxPageDataService.update(xcxPageData));
    }


    /**
     * 查询 根据主键 id 查询
     *
     * @author ling
     * @date 2025/01/15
     **/
    @GetMapping(value = "/{pdId}")
    public AjaxResult selectById(@PathVariable("pdId") String pdId) {

        if (pdId == null) {
            return error("参数为空");
        }
//        将字符串两边的空格去掉
        XcxPageData xcxPageData = xcxPageDataService.selectById(pdId.trim());
//        logger.info("查询结果为：{}", xcxPageData);
        return success(xcxPageData);
    }

    /**
     * 查询所有数据 分页查询(带条件)
     * 后台管理使用
     *
     * @author ling
     * @date 2025/01/15
     **/
    @GetMapping("/list")
    public TableDataInfo selectXcxPageDataList(XcxPageData xcxPageData) {
//        logger.info("查询所有数据 分页查询(带条件)：{}", xcxPageData);
        return xcxPageDataService.selectXcxPageDataList(xcxPageData);
    }

    /**
     * 获取图片数据
     * 小程序使用
     *
     * @return {@link AjaxResult }
     * @author ling
     * @date 2025/01/16
     */
    @GetMapping("/MP-List")
    public TableDataInfo getBanner(XcxPageData xcxPageData) {

        return xcxPageDataService.getMPList(xcxPageData);
    }

    /**
     * 图片上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public AjaxResult upload(@RequestParam("file") MultipartFile file) {
        AjaxResult ajaxResult = AjaxResult.success();
        logger.info("文件上传开始:{}", file);
        //        调用oss的文件上传方法
        try {
            //原始文件名字
            String originalFilename = file.getOriginalFilename();
            //截取原始文件名后缀
            int lastIndexOf = originalFilename.lastIndexOf(".");
            String extension = originalFilename.substring(lastIndexOf);
            //构造新文件的名称
            String objectName = UUID.randomUUID().toString() + extension;
            //        文件上传后返回的路径
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);

            return ajaxResult.put("filePath", filePath);
        } catch (IOException | ClientException e) {
            logger.error("文件上传失败：{}", e);
            return error("文件上传失败");
        }
    }

    /**
     * 删除bucket文件
     *
     * @param imgData 图像数据
     * @author ling
     * @date 2025/01/28
     */
    @DeleteMapping("/deleteBucketFile")
    public void deleteBucketFile(@RequestBody String[] imgData) {
        logger.info("删除Bucket数据：{}", (Object) imgData);
//        如果为空字符串
        if (imgData.length == 0) {
            return;
        }
//        处理数组数据
        for (String objName : imgData) {
            aliOssUtil.deleteFile(objName);
        }
    }

    /**
     * 统计页面数据
     *
     * @return {@link AjaxResult }
     * @author ling
     * @date 2025/04/28
     */
    @GetMapping("/statistics")
    public AjaxResult calculatePageData() {
//        获取素材的数量
        Long materialSize = materialService.calculateMaterial();
//        获取用户的数量
        Long userSize = userInfoService.calculateUser();
//        获取素材类型的数量
        Long materialTypeSize = materialTypeService.calculateMaterialType();
//        获取上传历史数量
        Long uploadHistorySize = uploadHistoryService.calculateUploadNum();
//        如果某个数据为空，则设为0
        materialSize = materialSize == null ? 0 : materialSize;
        userSize = userSize == null ? 0 : userSize;
        materialTypeSize = materialTypeSize == null ? 0 : materialTypeSize;
        uploadHistorySize = uploadHistorySize == null ? 0 : uploadHistorySize;
        AjaxResult ajaxResult = AjaxResult.success();
        return ajaxResult.put("materialSize", materialSize)
                .put("userSize", userSize)
                .put("materialTypeSize", materialTypeSize)
                .put("uploadHistorySize", uploadHistorySize)
                ;
    }

}
